package com.health.activity.settings;

import java.util.List;

import com.google.gson.Gson;
import com.health.NovaActivity;
import com.health.NovaApplication;
import com.health.R;
import com.health.adapter.UPDataMenuGridAdapter;
import com.health.db.FDbManager;
import com.health.model.UpDataReturn;
import com.health.tablebean.JTYSCustomerDoctorCont;
import com.health.tablebean.JTYSDoctorEvaluateBean;
import com.health.tablebean.JTYS_BASEINFO;
import com.health.tools.FTPTool;
import com.health.tools.GetPostJTYS;
import com.health.tools.GlobalConts;
import com.health.tools.GlobalContsJTYS;
import com.health.tools.JX_SJSC;
import com.health.tools.ResultTextDialog;
import com.health.tools.SPUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 数据上传（废弃）
 * 
 *
 */
public class DataUPMainActivity extends NovaActivity implements OnClickListener {
	private static final String TAG = "UpDataActivity";
	private static final int OX01 = 1;
	private static final int OX02 = 2;
	private static final int OX03 = 3;
	public static final String TYPE_JTQYYH = "TYPE_JTQYYH";
	public static final String TYPE_FWMYDPJ = "TYPE_FWMYDPJ";
	public static final String TYPE_CJYH = "TYPE_CJYH";
	private GridView gd_menu;
	private UPDataMenuGridAdapter menuAdapter;
	private TextView title;
	private Button btn_back;
	private ImageView img_photo;
	private TextView tv_name;
	private Thread mThread;
	static FDbManager fdbmanager = null;
	private int sumSize = 0;
	private int successCount = 0;
	private int failCount = 0;
	private int sumSize1 = 0;
	private int successCount1 = 0;
	private int failCount1 = 0;
	private int sumSize2 = 0;
	private int successCount2 = 0;
	private int failCount2 = 0;
	boolean isWorking = true;
	private String upType = "";
	private ResultTextDialog resultDialog;
	String serviceUrl = "";
	String methodName = "";
	String str_scData = "";
	private Button btn_up;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.jkjy_main_content);
		fdbmanager = NovaApplication.fdbmanger;
		findViews();
		addListeners();
	}

	@Override
	public void findViews() {
		gd_menu = (GridView) findViewById(R.id.gd_menu);
		title = (TextView) findViewById(R.id.title);
		title.setText("数据上传");

		img_photo = (ImageView) findViewById(R.id.img_photo);
		img_photo.setImageResource(R.drawable.upload_big);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_name.setText("数据上传");
		menuAdapter = new UPDataMenuGridAdapter(this, GlobalContsJTYS.MENU_UPLOAD);
		gd_menu.setAdapter(menuAdapter);
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_up = (Button) findViewById(R.id.btn_up);
		btn_up.setVisibility(View.GONE);
	}

	public void addListeners() {
		btn_back.setOnClickListener(this);
		// 菜单选项
		gd_menu.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (!GlobalConts.isNetworkAvailable(DataUPMainActivity.this)) {
					showTextDialog("请先检查网络");
					return;
				}
				cleanData();
				if (resultDialog == null) {
					resultDialog = new ResultTextDialog(DataUPMainActivity.this);
				}
				String result_type = "";
				if (position == 0) {
					// upType = TYPE_CJYH;
					// result_type = "建档用户";
					resultDialog.setText(result_type + "数据正在上传中，请稍后...");
					resultDialog.show();
					getDataUp();
				}
				// else if (position == 1) {
				// 老年人患者管理
				// upType = UpData.TYPE_LNR;
				// upType = TYPE_JTQYYH;
				// result_type = "家庭签约用户";
				// } else if (position == 2) {
				// upType = TYPE_FWMYDPJ;
				// result_type = "服务满意度评价";
				// }
				else if (position == 1) {
					// 上传公卫
					resultDialog.cancel();
					FTPTool.ftpUpdateDB(DataUPMainActivity.this);
					return;
				}
				
			}
		});
	}

	public void setDatas() {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;

		default:
			break;
		}

	}

	private void getDataUp() {

		new Thread(runnable1).start();// 线程启动
		new Thread(runnable2).start();
		new Thread(runnable3).start();

	}

	Runnable runnable1 = new Runnable() {

		@Override
		public void run() {// run()在新的线程中运行
			try {
				Log.e(TAG, "Runnable()......");
				// if (upType.equals(TYPE_JTQYYH)) {
				okHttp_postFromParameters();
				// } else if (upType.equals(TYPE_FWMYDPJ)) {
				// okHttp_postFromParameters_fwmydpj();
				// } else if (upType.equals(TYPE_CJYH)) {
				// okHttp_postFromParameters_CJYH();
				// }
				mHandler.sendEmptyMessage(OX01);
			} catch (Exception e) {
				e.printStackTrace();
				mHandler.sendEmptyMessage(OX03);
				return;
			}
		}
	};
	Runnable runnable2 = new Runnable() {

		@Override
		public void run() {// run()在新的线程中运行
			try {
				Log.e(TAG, "Runnable()......");
				okHttp_postFromParameters_fwmydpj();
				mHandler.sendEmptyMessage(OX01);
			} catch (Exception e) {
				e.printStackTrace();
				mHandler.sendEmptyMessage(OX03);
				return;
			}
		}
	};
	Runnable runnable3 = new Runnable() {

		@Override
		public void run() {// run()在新的线程中运行
			try {
				Log.e(TAG, "Runnable()......");
				okHttp_postFromParameters_CJYH();
				mHandler.sendEmptyMessage(OX01);
			} catch (Exception e) {
				e.printStackTrace();
				mHandler.sendEmptyMessage(OX03);
				return;
			}
		}
	};
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {// 此方法在ui线程运行
			switch (msg.what) {
			case OX01:
				if (resultDialog == null) {
					resultDialog = new ResultTextDialog(DataUPMainActivity.this);
				}
				resultDialog.setText("建档用户  上传数据总共" + sumSize + "条,上传成功" + successCount + "条,上传失败" + failCount + "条。\n"
						+ "签约用户  上传数据总共" + sumSize1 + "条,上传成功" + successCount1 + "条,上传失败" + failCount1 + "条。\n"
						+ "服务满意度  上传数据总共" + sumSize2 + "条,上传成功" + successCount2 + "条,上传失败" + failCount2 + "条。");
				resultDialog.showCancleLong();
				break;

			case OX02:

				break;
			case OX03:
				if (resultDialog == null) {
					resultDialog = new ResultTextDialog(DataUPMainActivity.this);
				}
				resultDialog.setText("暂无数据上传");
				resultDialog.showCancleShort();
				break;
			}
		}
	};

	private void cleanData() {
		sumSize = 0;
		successCount = 0;
		failCount = 0;
		sumSize1 = 0;
		successCount1 = 0;
		failCount1 = 0;
		sumSize2 = 0;
		successCount2 = 0;
		failCount2 = 0;
	}

	/**
	 * post请求，json数据为body
	 * 
	 * @param url
	 * @param json
	 * @param callback
	 */

	private void okHttp_postFromParameters() {
		// new Thread(new Runnable() {
		// @Override
		// public void run() {
		try {
			List<JTYSCustomerDoctorCont> conts = NovaApplication.fdbmanger.findAllByWhere(JTYSCustomerDoctorCont.class,
					"CREATER='" + SPUtil.getstr_jdrusername(DataUPMainActivity.this) + "' AND SIGN!='1'");
			if (conts.size() > 0) {

			} else {
				cleanData();
				return;
			}
			String json = new Gson().toJson(conts);

			// 请求完整url：http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
			String url = GlobalContsJTYS.getUrlPost_JTYS() + GetPostJTYS.URL_JTYS_SCQYSJ + "/";
			System.out.println(url + "?jsonkey=" + json);
			OkHttpClient okHttpClient = new OkHttpClient();
			RequestBody formBody = new FormBody.Builder().add("jsonkey", json).build();
			Request request = new Request.Builder().url(url).post(formBody).build();
			okhttp3.Response response = okHttpClient.newCall(request).execute();
			// Log.i(TAG, "接口返回的 的的" + response.body().string());
			String result = response.body().string();
			Log.e(TAG, "接口返回的 的的" + result);

			UpDataReturn updata = JX_SJSC.jxJTQYYSData(result);
			if (updata != null) {
				sumSize1 = updata.getSize();
				successCount1 = updata.getSuccessCount();
				failCount1 = updata.getFailCount();
				Log.e("tag", sumSize1 + "sumSize1" + successCount1 + "successCount1" + failCount1 + "failCount1");
			} else {
				cleanData();
			}
			// List<JTYSCustomerDoctorCont> users = new
			// Gson().fromJson(infor,
			// new TypeToken<List<JTYSCustomerDoctorCont>>() {
			// }.getType());
			//
			// for (JTYSCustomerDoctorCont jtys : users) {
			//
			// jtys.setSign("1");
			// Log.e(TAG, jtys.toString());
			// NovaApplication.fdbmanger.updata(jtys);
			// }

		} catch (Exception e) {

			e.printStackTrace();
		}
		// }
		// }).start();
	}

	/**
	 * 服务满意度评价
	 * 
	 * @author 王婷婷
	 * @date 2017年6月5日 下午2:24:17
	 */
	private void okHttp_postFromParameters_fwmydpj() {
		try {
			List<JTYSDoctorEvaluateBean> conts = NovaApplication.fdbmanger.findAllByWhere(JTYSDoctorEvaluateBean.class,
					"CREATER='" + NovaApplication.getJgrno() + "' AND SIGN ='0'");
			if (conts.size() > 0) {

			} else {
				cleanData();
				return;
			}
			String json = new Gson().toJson(conts);

			// 请求完整url：http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
			String url = GlobalContsJTYS.getUrlPost_JTYS() + GetPostJTYS.URL_JTYS_FWMYDPJ + "/";
			System.out.println(url + "?jsonkey=" + json);
			OkHttpClient okHttpClient = new OkHttpClient();
			RequestBody formBody = new FormBody.Builder().add("jsonkey", json).build();
			Request request = new Request.Builder().url(url).post(formBody).build();
			okhttp3.Response response = okHttpClient.newCall(request).execute();
			// Log.i(TAG, "接口返回的 的的" + response.body().string());
			UpDataReturn updata = JX_SJSC.jxFwmydData(response.body().string());
			if (updata != null) {
				sumSize2 = updata.getSize();
				successCount2 = updata.getSuccessCount();
				failCount2 = updata.getFailCount();
				Log.e("tag", sumSize2 + "sumSize2" + successCount2 + "successCount2" + failCount2 + "failCount2");
			} else {
				cleanData();
			}
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	/**
	 * 创建用户上传
	 * 
	 * @author 王婷婷
	 * @date 2017年6月5日 下午2:24:17
	 */
	private void okHttp_postFromParameters_CJYH() {
		try {
			List<JTYS_BASEINFO> conts = NovaApplication.fdbmanger.findAllByWhere(JTYS_BASEINFO.class,
					"CREATER='" + NovaApplication.getJgrno() + "' AND SIGN ='0'");

			if (conts.size() > 0) {

			} else {
				cleanData();
				return;
			}
			String json = new Gson().toJson(conts);
			String url = GlobalContsJTYS.getUrlPost_JTYS() + GetPostJTYS.URL_JTYS_CJDA_LIST;
			System.out.println(url + "?jsonkey=" + json);
			OkHttpClient okHttpClient = new OkHttpClient();
			RequestBody formBody = new FormBody.Builder().add("jsonkey", json).build();
			Request request = new Request.Builder().url(url).post(formBody).build();
			okhttp3.Response response = okHttpClient.newCall(request).execute();
			Log.i(TAG, "接口返回的 的的" + response.body().string());
			UpDataReturn updata = JX_SJSC.jxCJYHData(response.body().string());
			if (updata != null) {
				sumSize = updata.getSize();
				successCount = updata.getSuccessCount();
				failCount = updata.getFailCount();
				Log.e("tag", sumSize + "sumSize" + successCount + "successCount" + failCount + "failCount");
			} else {
				cleanData();
			}
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	@Override
	public void setListeners() {
		// TODO Auto-generated method stub
	}
}
